import Service from "./Service";
import UrlMgr from "./UrlMgr";

export default class HttpHandler {
    private _successHandle: any | null = null;
    private _failHandle: any | null = null;
    private _requestType: any = null;
    private _requestData: any = null;
    private _retry: boolean = false;

    constructor(e, t, a) {
        this.setHandler(e, t, a);
    }

    setHandler(e, t, a) {
        this.setRequest(e);
        this._successHandle = t;
        this._failHandle = a;
        return this;
    };
    setRequest(e) {
        this._requestType = e;
        this._requestData = null;
        this._retry = UrlMgr.getInstance().needEnqueue(this._requestType);
        return this;
    };
    setRequestData(e) {
        void 0 === e && (e = null);
        this._requestData = e;
        return this;
    };
    setRetry(e) {
        this._retry = e;
        return this;
    };
    success(e) {
        this._successHandle && this._successHandle.runWith(e);
        this.recover();
        return false;
    };
    fail(e) {
        this._failHandle && this._failHandle.runWith(e);
        if (this._retry) return true;
        this.recover();
        return false;
    };
    needRetry() {
        return this._retry;
    };
    enterQueue() {
        return UrlMgr.getInstance().needEnqueue(this._requestType);
    };
    getRequestType() {
        return this._requestType;
    };
    getRequestData() {
        return this._requestData;
    };
    clear() {
        this._requestType = null;
        this._requestData = null;
        this._successHandle && this._successHandle.recover();
        this._failHandle && this._failHandle.recover();
        return this;
    };
    recover() {
        HttpHandler._pool.push(this.clear());
    };

    handleRequest() {
        Service.request(this);
    };
    static create(t, a, o) {
        return HttpHandler._pool.length ? HttpHandler._pool.pop().setHandler(t, a, o) : new HttpHandler(t, a, o);
    }
    private static _pool: HttpHandler[] = [];
}
